﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using LDSP.BRL;
using System.Data;
using System.IO;
using LDSP.Helper;
using BLL.Util;

namespace LDSP.UI.EnterpriseAdmin
{
    public partial class AddTaskPlan : BRL.BaseEnterprisePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!IsPostBack)
                {
                    this.CheckQS();
                }
                if (this.RB())
                {
                    this.InitDataDynamicBefore();
                    if (!IsPostBack)
                    {
                        this.InitDataSelect();
                    }
                }
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }

        protected Plan m_plan = null;
        protected Plan m_orginalplan = null;
        protected R_EnterpriseCodification m_r_enterpriseCodification = null;
        protected Codification m_Codification = null;

        /// <summary>
        /// Plan的id
        /// </summary>
        protected int LastID
        {
            get { return this.GetVSInt("LastID"); }
            set
            {
                this.SetVS("LastID", value);
                m_plan = null;
            }
        }
        protected int CodID
        {
            get { return this.GetVSInt("CodID"); }
            set
            {
                this.SetVS("CodID", value);
                m_Codification = null;
            }
        }
        protected int FavoriteID
        {
            get { return this.GetVSInt("FavoriteID"); }
            set
            {
                this.SetVS("FavoriteID", value);
                m_r_enterpriseCodification = null;
            }
        }
        /// <summary>
        /// 选中的企业的id
        /// </summary>
        protected int EnterpriseID
        {
            get { return this.GetVSInt("EnterpriseID"); }
            set
            {
                this.SetVS("EnterpriseID", value);
            }
        }
        protected Plan Plan
        {
            get
            {
                if (m_plan == null)
                {
                    m_plan = new Plan();
                    if (LastID != 0)
                    {
                        m_plan.GetProperties(LastID);
                    }
                }
                return m_plan;
            }
        }
        protected Plan OriginalPlan
        {
            get
            {
                if (m_orginalplan == null)
                {
                    m_orginalplan = new Plan();
                }
                return m_orginalplan;
            }
            set
            {
                m_orginalplan = value;
            }
        }
        protected R_EnterpriseCodification R_EnterpriseCodification
        {
            get
            {
                if (m_r_enterpriseCodification == null)
                {
                    m_r_enterpriseCodification = new R_EnterpriseCodification();
                    if (FavoriteID != 0)
                    {
                        m_r_enterpriseCodification.GetProperties(FavoriteID);
                    }
                }
                return m_r_enterpriseCodification;
            }
        }
        protected Codification Codification
        {
            get
            {
                if (m_Codification == null)
                {
                    m_Codification = new Codification();
                    if (CodID != 0)
                    {
                        m_Codification.GetProperties(CodID);
                    }
                }
                return m_Codification;
            }
        }
        protected bool IsAdd
        {
            get { return LastID == 0; }
        }
        protected string OriginalIds
        {
            get { return this.GetVSString("OriginalIds"); }
            set
            {
                this.SetVS("OriginalIds", value);
            }
        }
        protected bool IsEnterpriseGroupAdmin
        {
            get
            {
                return this.LoginUser != null && this.LoginUser.Enterprise != null && this.LoginUser.Enterprise.IsEnterpriseGroup == true;
            }
        }

        protected void CheckQS()
        {
            if (!IsEnterpriseGroupAdmin)
            {
                FavoriteID = this.GetInt(this.Request.QueryString["fid"]);
                if (R_EnterpriseCodification.ID == 0)
                {
                    FavoriteID = 0;
                }
            }
            else
            {
                CodID = this.GetInt(this.Request.QueryString["fid"]);
                if (Codification.ID == 0)
                {
                    CodID = 0;
                }
            }

            LastID = this.GetInt(this.Request.QueryString["pid"]);
            if (Plan.ID == 0)
            {
                LastID = 0;
            }
            else
            {
                FavoriteID = Plan.FavoriteID;
            }
        }
        protected bool RB()
        {
            bool res = true;

            //对于非集团用户，任务计划只可以建立在适用法规上面
            if (IsEnterpriseGroupAdmin == false && R_EnterpriseCodification.EnterpriseID != LoginUser.EnterpriseID)
            {
                this.JSAlert("请选择合适的法律法规/标准来添加计划！");
                this.JSCloseWindow();
                res = false;
            }
            return res;
        }
        protected void InitDataDynamicBefore()
        {
            this.AutoCompleteExtender1.ContextKey = this.LoginUser.EnterpriseID.ToString();

            this.JSSetDateTimeReadOnly(this.txt_person.ClientID);
        }
        protected void SetStatus()
        {
            this.lbl_op.Text = IsAdd ? "【添加】" : "【修改】";
            this.lbl_op.Style["color"] = IsAdd ? "red" : "blue";

            bool isAdmin = this.LoginUser.UserType == EnterpriseUserType.企业管理员;
            this.txt_name.ReadOnly = !isAdmin;
            this.txt_person.ReadOnly = !isAdmin;
            this.txt_department.ReadOnly = !isAdmin;
            this.btn_ResponsibleChoosen.Enabled = isAdmin;
            this.btn_add.Visible = isAdmin;
            this.td_subdiary.Visible = IsEnterpriseGroupAdmin;
            this.ddl_subdiary.Enabled = false;//此字段不可编辑

            //如果不是集团用户或者不是在添加，那么显示下列列表。否则显示checkbox。
            this.ddl_subdiary.Visible = !IsEnterpriseGroupAdmin || !IsAdd;
            this.chk_subdiary_list.Visible = IsEnterpriseGroupAdmin && IsAdd;

            this.ClientComfirm(this.btn_ok, string.Format("您确定执行{0}操作吗？", IsAdd ? "添加" : "修改"));
        }
        protected void InitDataSelect()
        {
            CommonControlInitial.InitialTaskStatus(this.ddlStatus);

            //将未开始的全部改为进行中，去掉未开始这个状态。
            if (Plan.Status == (int)TaskStatus.未开始)
            {
                Plan.Status = (int)TaskStatus.进行中;
            }

            //对于企业集团用户，初始化下列列表并找到当前应显示的企业，或者企业多选框
            if (IsEnterpriseGroupAdmin)
            {
                if (IsAdd)
                {
                    this.InitSubdiaryList();
                }
                else
                {
                    BindDDLSubdiary();

                    //设定子公司名称
                    R_EnterpriseCodification ec = new R_EnterpriseCodification();
                    ec.GetProperties(Plan.FavoriteID);
                    this.ddl_subdiary.SelectedValue = ec.EnterpriseID.ToString();

                    EnterpriseID = ec.EnterpriseID;
                }
            }
            else
            {
                EnterpriseID = this.LoginUser.EnterpriseID;
            }

            //记录查看时间
            R_User_ViewPlan uvp = new R_User_ViewPlan().GetByUserAndPlan(this.LoginUser.ID, Plan.ID);
            if (uvp == null)
            {
                uvp = new R_User_ViewPlan();
                uvp.UserId = this.LoginUser.ID;
                uvp.PlanId = Plan.ID;
                uvp.ViewDT = DateTime.Now;
                uvp.Add();
            }
            else
            {
                uvp.ViewDT = DateTime.Now;
                uvp.Update();
            }

            this.JSShowModalDialog(string.Format("id={0}&enterpriseid={1}", LastID, EnterpriseID), this.btn_ResponsibleChoosen);

            this.txt_name.Text = Plan.Name;
            this.txt_department.Text = Plan.Department;
            this.txt_expiredDT.Text = this.FormatDT(Plan.ExpiredDT);
            this.txt_progress.Text = Plan.Progress;
            this.txt_comment.Text = Plan.Comment;
            this.txt_email.Text = Plan.Email;
            this.lblReference.Text = GetCodificationReference();
            this.ddlStatus.SelectedValue = ((TaskStatus)Plan.Status).ToString();

            this.InitPrincipleList();
            this.SetStatus();

            //缓存现有的Plan以便与修改后的Plan比对。
            this.hdPlanName.Value = Plan.Name;
            this.hdDepartment.Value = Plan.Department;
            this.hdExpireDT.Value = this.FormatDT(Plan.ExpiredDT);
            this.hdProgress.Value = Plan.Progress;
            this.hdComment.Value = Plan.Comment;
            this.hdStatus.Value = ((TaskStatus)Plan.Status).ToString();
            this.hdPerson.Value = Plan.Person;
        }

        private string GetCodificationReference()
        {
            string reference = string.Empty;

            //如果是标准，则显示对应标准的概述。
            //如果是法规，是集团管理员，且在添加任务计划，则显示对应法规的关键条款。
            //其他情况，显示适用法规的关键条款。
            Codification cod = R_EnterpriseCodification.Codification;
            if (cod.ID == 0)
            {
                cod = Codification;
            }

            if (cod.DocType == DocType.标准)
            {
                reference = cod.Summary;
            }
            else if (IsEnterpriseGroupAdmin && IsAdd)
            {
                reference = cod.KeyItems;
            }
            else
            {
                reference = string.IsNullOrEmpty(R_EnterpriseCodification.KeyItems) ? cod.KeyItems : R_EnterpriseCodification.KeyItems;
            }

            if (reference == string.Empty)
            {
                reference = "无";
            }

            reference = reference.Replace("\r\n", "</br>");

            return reference;
        }

        private void InitSubdiaryList()
        {
            DataTable dt = new Enterprise().GetRecords("parentID=" + this.LoginUser.EnterpriseID);
            this.chk_subdiary_list.DataSource = dt;
            this.chk_subdiary_list.DataTextField = "Code";
            this.chk_subdiary_list.DataValueField = "Id";
            this.chk_subdiary_list.DataBind();
        }

        protected void BindDDLSubdiary()
        {
            CommonControlInitial.InitialSubdiary(this.ddl_subdiary, this.LoginUser.Enterprise.GetSubsidiaryList());
        }
        private void JSShowModalDialog(string arg, WebControl ctrl)
        {
            this.JSShowDialog(string.Format("../UserManagement/MngEnterpriseUser.aspx?type=1&PageID={0}&{1}", PageID, arg), 700, 800, ctrl, null, null, null, null, null, null, null, true, null, null, null, null, null);
        }
        protected void InitPrincipleList()
        {
            int planId = LastID > 0 ? LastID : -1;

            List<R_PlanPrinciple> principleList = new R_PlanPrinciple().GetListByPlan(planId);
            List<string> list = new List<string>();
            for (int i = 0; i < principleList.Count; i++)
            {
                list.Add(principleList[i].UserID.ToString());
            }
            this.OriginalIds = this.CombineStrS(list);
            this.UserList(PageID, OriginalIds);
            this.ShowPrincipleList();
        }
        protected void ValidateDataBefore()
        {
            if (IsEnterpriseGroupAdmin && IsAdd)
            {
                bool find = false;
                foreach (ListItem item in this.chk_subdiary_list.Items)
                {
                    if (item.Selected == true)
                    {
                        find = true;
                        break;
                    }
                }

                if (find == false)
                {
                    throw new BYFW.BOL.CustomException("请选择子公司！");
                }
            }
        }
        protected void ValidateDataAfter()
        {
            if (Plan.Name == "")
            {
                throw new BYFW.BOL.CustomException("名称不能为空！");
            }
        }

        private void ShowPrincipleList()
        {
            List<string> idList = this.SplitStrS(this.UserList(PageID));
            List<string> nameList = new List<string>();
            for (int i = 0; i < idList.Count; i++)
            {
                int id = this.GetInt(idList[i]);
                EnterpriseUser ett = new EnterpriseUser();
                ett.GetProperties(id);
                nameList.Add(ett.Name);
            }
            this.txt_person.Text = this.CombineStrS(nameList);
        }
        protected void SetData()
        {
            this.ValidateDataBefore();
            Plan.Name = this.txt_name.Text.Trim();
            Plan.Comment = this.txt_comment.Text;
            Plan.ChangeDT = DateTime.Now;
            Plan.Department = this.txt_department.Text;
            Plan.ExpiredDT = DateTime.Parse(this.txt_expiredDT.Text.Trim());
            Plan.Progress = this.txt_progress.Text;
            Plan.Status = (int)Enum.Parse(typeof(TaskStatus), this.ddlStatus.SelectedValue);
            Plan.Email = this.txt_email.Text.Replace("；", ";");

            Plan.FavoriteID = FavoriteID;

            this.ValidateDataAfter();
        }
        private void SetPrinciples()
        {
            //删除旧责任人信息。
            List<R_PlanPrinciple> relation = new R_PlanPrinciple().GetListByPlan(Plan.ID);
            List<string> ids = new List<string>();
            foreach (R_PlanPrinciple r_planPrinciple in relation)
            {
                r_planPrinciple.Delete();
            }

            //添加新责任人信息。
            string principleList = this.UserList(PageID);
            string currentPrinciples = string.Empty;
            string[] principles = principleList.Split(';');
            foreach (String p in principles)
            {
                int userid = 0;
                Int32.TryParse(p.Trim(), out userid);

                //查看用户是否属于当前企业
                EnterpriseUser user = new EnterpriseUser();
                user.GetProperties(new EnterpriseUser().GetRecordByID(userid));

                //责任人字符串不为空且用户有效且用户属于当前企业，则添加成责任人
                if (!string.IsNullOrEmpty(p) && userid > 0 && user.EnterpriseID == EnterpriseID)
                {
                    R_PlanPrinciple r = new R_PlanPrinciple();
                    r.PlanID = Plan.ID;
                    r.UserID = userid;
                    r.Add();

                    currentPrinciples += user.Name + ";";
                }
            }

            Plan.Person = currentPrinciples;
            Plan.Update();
        }
        protected void Add()
        {
            string alertMessage = "成功添加任务计划!";

            //集团用户新加任务
            if (IsEnterpriseGroupAdmin && FavoriteID == 0)
            {
                List<int> subdiaryList = new List<int>();
                foreach (ListItem item in this.chk_subdiary_list.Items)
                {
                    if (item.Selected == true) subdiaryList.Add(Int32.Parse(item.Value));
                }

                foreach (int subdiaryId in subdiaryList)
                {
                    EnterpriseID = subdiaryId;

                    CreateFavorateCod(subdiaryId);
                    SetData();

                    Plan.Add();
                    SetPrinciples();
                    alertMessage = SendMail(true);
                }
            }
            else
            {
                SetData();
                Plan.Add();
                SetPrinciples();
                alertMessage = SendMail(true);
            }

            this.FavoriteID = 0;
            this.LastID = 0;
            this.JSAlert(alertMessage);
        }

        private void CreateFavorateCod(int subdiaryId)
        {
            R_EnterpriseCodification r_eg = new R_EnterpriseCodification().GetPropertiesByEnterpriseAndCodification(subdiaryId, CodID);

            if (r_eg.ID == 0)
            {
                var publicFavoriteInfo = new PublicFavoriteInfo();
                publicFavoriteInfo.Comment = "集团指派任务";
                this.PublicFavoriteInfo(PageID, publicFavoriteInfo);

                Enterprise en = new Enterprise();
                en.GetProperties(subdiaryId);

                r_eg = AddFavirote(false, Codification, en);
            }

            FavoriteID = r_eg.ID;

            Plan.Type = (int)TaskPlanType.指派;
        }

        protected void Update()
        {
            this.SetData();
            Plan.Update();
            SetPrinciples();
            string alertMessage = SendMail(false);

            this.JSAlert(alertMessage);
        }

        private string SendMail(bool isAdd)
        {
            //记录邮箱使用次数
            string[] emails = !string.IsNullOrEmpty(Plan.Email) ? Plan.Email.Replace("；", ";").Split(';') : new string[0];
            if (emails.Length > 0)
            {
                foreach (string email in emails)
                {
                    if (!string.IsNullOrEmpty(email))
                    {
                        new EnterpriseEmails().IncreaseWordsCount(email, this.LoginUser.EnterpriseID);
                    }
                }
            }

            string alertMessage = isAdd ? "添加成功！" : "修改成功！";
            if (this.chbNeedNotify.Checked
                && !string.IsNullOrEmpty(this.txt_email.Text))
            {
                String subject = isAdd ? "新建任务计划 - " + Plan.Name : "任务计划 - " + Plan.Name + " 已更新";
                String content = GenerateMailContent(subject, isAdd);
                IList<string> bcc = new List<string>() { Plan.Email };
                
                //发送邮件给手动输入的邮箱和责任人的邮箱。
                List<R_PlanPrinciple> users = new R_PlanPrinciple().GetListByPlan(Plan.ID);
                foreach (R_PlanPrinciple user in users) {
                    EnterpriseUser u = new EnterpriseUser();
                    u.GetProperties(new EnterpriseUser().GetRecordByID(user.UserID));
                    if (!string.IsNullOrEmpty(u.Email))
                    {
                        bcc.Add(u.Email);
                    }
                }

                MailSender.SendMail(bcc, subject, content, null, null, true);

                alertMessage = isAdd ? "添加成功, 邮件已发送!" : "更新成功, 邮件已发送!";
            }

            return alertMessage;
        }

        private string GenerateHtmlRow(string first, string second, string third)
        {
            return StringUtil.GenerateHtmlRow(new List<string>() { first, second, third });
        }

        private string GenerateHtmlBoldRow(string first, string second, string third)
        {
            return StringUtil.GenerateHtmlBoldRow(new List<string>() { first, second, third });
        }

        private string GenerateMailContent(String subject, bool isAdd)
        {
            string content = subject + ", 请查看" + HttpContext.Current.Request.Url.Host + "。" + "<br/>";

            content += "<br/>详细信息:<br/>";
            content += "<table style=\"border: 0px solid #000000; border-collapse: collapse;\">";
            content += GenerateHtmlBoldRow("栏目名称", "更新前", "更新后");

            if (isAdd)
            {
                content += GenerateHtmlRow("任务名称", "", Plan.Name);//"<tr><td >任务名称</td><td></td><td>" + Plan.Name + "</td>";
                content += !string.IsNullOrEmpty(Plan.Person) ? GenerateHtmlRow("责任人", "", Plan.Person) : string.Empty;
                content += !string.IsNullOrEmpty(Plan.Department) ? GenerateHtmlRow("执行部门/人员", "", Plan.Department) : string.Empty;
                content += GenerateHtmlRow("到期时间", "", Plan.ExpiredDT.ToShortDateString());
                content += !string.IsNullOrEmpty(Plan.Progress) ? GenerateHtmlRow("项目进度概述", "", Plan.Progress) : string.Empty;
                content += GenerateHtmlRow("状态", "", ((TaskStatus)Plan.Status).ToString());
                content += !string.IsNullOrEmpty(Plan.Comment) ? GenerateHtmlRow("备注", "", Plan.Comment) : string.Empty;
            }
            else
            {
                //收集旧Plan的值
                OriginalPlan.Name = this.hdPlanName.Value;
                OriginalPlan.Person = this.hdPerson.Value;
                OriginalPlan.Department = this.hdDepartment.Value;
                OriginalPlan.ExpiredDT = DateTime.Parse(this.hdExpireDT.Value);
                OriginalPlan.Progress = this.hdProgress.Value;
                OriginalPlan.Status = (int)Enum.Parse(typeof(TaskStatus), this.hdStatus.Value);
                OriginalPlan.Comment = this.hdComment.Value;


                content += OriginalPlan.Name != Plan.Name ? GenerateHtmlRow("任务名称", OriginalPlan.Name, Plan.Name) : string.Empty;
                content += OriginalPlan.Person != Plan.Person ? GenerateHtmlRow("责任人", OriginalPlan.Person, Plan.Person) : string.Empty;
                content += OriginalPlan.Department != Plan.Department ? GenerateHtmlRow("执行部门/人员", OriginalPlan.Department, Plan.Department) : string.Empty;
                content += OriginalPlan.ExpiredDT.ToShortDateString() != Plan.ExpiredDT.ToShortDateString() ? GenerateHtmlRow("到期时间", OriginalPlan.ExpiredDT.ToShortDateString(), Plan.ExpiredDT.ToShortDateString()) : string.Empty;
                content += OriginalPlan.Progress != Plan.Progress ? GenerateHtmlRow("项目进度概述", OriginalPlan.Progress, Plan.Progress) : string.Empty;
                content += OriginalPlan.Status != Plan.Status ? GenerateHtmlRow("状态", ((TaskStatus)OriginalPlan.Status).ToString(), ((TaskStatus)Plan.Status).ToString()) : string.Empty;
                content += OriginalPlan.Comment != Plan.Comment ? GenerateHtmlRow("备注", OriginalPlan.Comment, Plan.Comment) : string.Empty;
            }
            content += "</table><br/>";

            content += "更新者: " + this.LoginUser.Name + "<br/>";
            content += "更新时间：" + string.Format(LDSP.Util.Constants.Info.Mail_Postfix, DateTime.Now.ToShortDateString());

            return content;
        }

        protected void btn_add_Click(object sender, EventArgs e)
        {
            try
            {
                this.LastID = 0;
                this.InitDataSelect();
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }
        protected void btn_ok_Click(object sender, EventArgs e)
        {
            try
            {
                if (IsAdd)
                {
                    ValidateDataBefore();
                    this.Add();
                }
                else
                {
                    this.Update();
                }
                this.InitDataSelect();

                this.JSCloseWindow();
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }
        protected void btn_ResponsibleChoosen_Click(object sender, EventArgs e)
        {
            this.ShowPrincipleList();
        }

        protected void ddl_subdiary_SelectedIndexChanged(object sender, EventArgs e)
        {
            //对于集团管理员，如果没有选子公司，则默认当前选中企业为集团
            this.EnterpriseID = Int32.Parse(this.ddl_subdiary.SelectedValue);
            if (this.EnterpriseID == 0)
            {
                this.EnterpriseID = this.LoginUser.EnterpriseID;
            }

            this.JSShowModalDialog(string.Format("id={0}&enterpriseid={1}", LastID, EnterpriseID), this.btn_ResponsibleChoosen);
        }
    }
}